<script lang="ts" setup>
import { reactive, ref, watch, markRaw } from "vue"
import {
  createOrderDataApi,
  updateOrderDataApi,
  updateOrderDataApiZc,
  getOrderDataApi,
  getOrderOneApi,
  downLoadOrderTable,
  getOrdeCode
} from "@/api/order"
import { getRiskByCardIdApi } from "@/api/RiskControlCenter"
import { type IGetOrderData } from "@/api/order/types/order"
import { type IGetComboData } from "@/api/combo/types/combo"
import { type FormInstance, type FormRules, ElMessage } from "element-plus"
import { Search, Refresh, CirclePlus, Download, RefreshRight, UploadFilled, Folder } from "@element-plus/icons-vue"
import { usePagination } from "@/hooks/usePagination"
import { useUserStore } from "@/store/modules/user"
import { useCommonStore } from "@/store/modules/common"
import { useComboStore } from "@/store/modules/combo"
import { useTeamStore } from "@/store/modules/team"
import { checkPhoneNumber, checkID, isAddressDetailed } from "@/utils/validate"
import { getToken } from "@/utils/cache/cookies"
import { IdCard } from "@/utils/getCardId"
import { uploadCidImageList } from "@/api/order"
import { formatDateTime } from "@/utils"
// import { getCurrentInstance } from "vue"
import useDraw from "@/utils/useDraw"
import { dateUtil } from "@/utils/index"
import * as echarts from "echarts/core"
import {
  TitleComponent,
  // TitleComponentOption,
  ToolboxComponent,
  // ToolboxComponentOption,
  TooltipComponent,
  // TooltipComponentOption,
  GridComponent,
  // GridComponentOption,
  LegendComponent
  // LegendComponentOption
} from "echarts/components"
import { LineChart } from "echarts/charts"
import { UniversalTransition } from "echarts/features"
import { CanvasRenderer } from "echarts/renderers"

echarts.use([
  TitleComponent,
  ToolboxComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  LineChart,
  CanvasRenderer,
  UniversalTransition
])

// type EChartsOption = echarts.ComposeOption<
//   | TitleComponentOption
//   | ToolboxComponentOption
//   | TooltipComponentOption
//   | GridComponentOption
//   | LegendComponentOption
//   | LineSeriesOption
// >

//报表
// * 适配处理
const { calcRate, windowDraw, unWindowDraw } = useDraw()
const eacharts1 = ref()
const myChart = ref<any>()
const renderChart = () => {
  if (myChart.value == null) {
    const myDom = eacharts1.value
    // myChart.value = proxy.$echarts.init(myDom)
    myChart.value = markRaw(echarts.init(myDom))
  }
  myChart.value.setOption(chartOption, true)
}

const chartOption = {
  tooltip: {
    trigger: "axis"
  },
  legend: {
    data: ["Email", "Union Ads", "Video Ads", "Direct", "Search Engine"]
  },
  grid: {
    left: "3%",
    right: "4%",
    bottom: "3%",
    containLabel: true
  },
  toolbox: {
    feature: {
      saveAsImage: {}
    }
  },
  xAxis: {
    type: "category",
    boundaryGap: false,
    data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
  },
  yAxis: {
    type: "value"
  },
  series: [
    {
      name: "Email",
      type: "line",
      stack: "Total",
      data: [0, 0, 0, 1, 0, 0, 0]
    },
    {
      name: "Union Ads",
      type: "line",
      stack: "Total",
      data: [0, 0, 0, 51, 0, 0, 0]
    },
    {
      name: "Video Ads",
      type: "line",
      stack: "Total",
      data: [0, 0, 0, 0, 0, 0, 0]
    }
  ]
}

function chartRun(xAxisData: any, legend: any, series: any) {
  if (xAxisData.length > 12) {
    ElMessage.error("日期过长")
    return false
  }
  chartOption.xAxis.data = xAxisData
  chartOption.legend.data = legend
  chartOption.series = series

  return true
}

// 生命周期
const chartEvent = {
  mounted: () => {
    windowDraw()
    calcRate()
    renderChart()
  },
  unmounted: () => {
    myChart.value = null
    unWindowDraw()
  }
}
//end

defineOptions({
  name: "OrderList"
})
const loading = ref<boolean>(false)
const commonStore = useCommonStore()
const comboStore = useComboStore()
const comboList = ref<IGetComboData[]>([])
const payDate = ref("")
const seeState = ref("")
const comboStr = ref<string>("")
//团队列表
const teamList = ref<any>(useTeamStore().teamListStore)
//规则列表
const roleList = [
  {
    id: 0,
    name: "按日生成"
  },
  {
    id: 1,
    name: "按星期生成"
  },
  {
    id: 2,
    name: "按月生成"
  }
]

/**日期相关 */
const size = ref<"default" | "large" | "small">("default")
// new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)
const DATE = new Date()
const Y = ref<any>(DATE.getFullYear())
const M = ref<any>(DATE.getMonth())
const D = ref<any>(DATE.getDate())
const shortcuts = [
  {
    text: "当天",
    value: () => {
      const end = new Date(Y.value, M.value, D.value, 23, 59, 59)
      const start = new Date(Y.value, M.value, D.value, 0, 0, 0)
      start.setTime(start.getTime())
      return [start, end]
    }
  },
  {
    text: "昨天",
    value: () => {
      const end = new Date(Y.value, M.value, D.value, 23, 59, 59)
      const start = new Date(Y.value, M.value, D.value, 0, 0, 0)
      start.setTime(start.getTime() - 3600 * 1000 * 24)
      end.setTime(end.getTime() - 3600 * 1000 * 24)
      return [start, end]
    }
  },
  {
    text: "上周",
    value: () => {
      const end = new Date(Y.value, M.value, D.value, 23, 59, 59)
      const start = new Date(Y.value, M.value, D.value, 0, 0, 0)
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: "上个月",
    value: () => {
      const end = new Date(Y.value, M.value, D.value, 23, 59, 59)
      const start = new Date(Y.value, M.value, D.value, 0, 0, 0)
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  },
  {
    text: "三个月",
    value: () => {
      const end = new Date(Y.value, M.value, D.value, 23, 59, 59)
      const start = new Date(Y.value, M.value, D.value, 0, 0, 0)
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    }
  }
]

/**END */
const uploadheaders = ref<any>({
  token: getToken()
})
const codeList = ref<any>([])
/**-------- */
const getCodeList = () => {
  getOrdeCode().then((res: any) => {
    // console.log(res)
    codeList.value = res.data
  })
}
getCodeList()
/**END */

const fileList0 = ref<any>([]) //身份证正面
const fileList1 = ref<any>([]) //身份证反面
const fileList2 = ref<any>([]) //人像
// ****************订单批量上传*******************************
import { genFileId } from "element-plus"
import type { UploadInstance, UploadProps, UploadRawFile } from "element-plus"

const upload = ref<UploadInstance>()

const handleExceed: UploadProps["onExceed"] = (files) => {
  upload.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  upload.value!.handleStart(file)
}
const handleSucc = () => {
  getTableData()
  // loading.value = false
  ElMessage.success("上传成功！")
}

const submitUpload = () => {
  // loading.value = true
  upload.value!.submit()
}
// *********************订单上传结束*************************

const formatterCombo = (row: any, column: any, celValue: any) => {
  comboList.value.filter((item: any) => {
    if (item.id == row.sku) {
      celValue = item.name
    }
  })
  return celValue
}
const comboSkuToStr = (row: any) => {
  comboList.value.filter((item: any) => {
    if (item.id == row.sku) {
      comboStr.value = item.name
    }
  })
}

const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()

//#region 增
const dialogVisible = ref<boolean>(false)
const formRef = ref<FormInstance | null>(null)
const userStore = useUserStore()
// console.log(userStore.teamName)
const formData = reactive({
  orderId: "",
  source: "",
  iccid: "",
  handleMobile: "",
  sku: "",
  cardName: "",
  cardId: "",
  consignee: "",
  takeMobile: "",
  takeAddress: "",
  state: "",
  activate: "",
  kickback: "",
  superiorId: "",
  update: new Date(),
  superiorName: "",
  note: "",
  cardFront: "",
  cardBack: "",
  photo: "",
  chargingState: "",
  chargingDate: new Date(payDate.value),
  result: "",
  logisticsCompany: "",
  logisticsId: "",
  commissionState: "",
  recorder: "",
  salesman: "", //业务员
  remark: "", //备注
  activeData: "", //激活数据
  //规则
  dataRole: "",
  //日期
  dayDate: "",
  //周
  startWeekDate: "",
  endWeekDate: "",
  //团队列表
  teamList: [],
  //订单状态
  orderState: ""
})
const formRules: FormRules = reactive({
  orderId: [{ required: true, trigger: "blur", message: "请输入订单名称" }],
  cardName: [{ required: true, trigger: "blur", message: "请填写姓名" }],
  consignee: [{ required: true, trigger: "blur", message: "请填写收货名" }],
  sku: [{ required: true, trigger: "blur", message: "请选择套餐" }],
  // handleMobile: [{ required: true, validator: checkPhoneNumber, trigger: "blur" }],
  cardId: [{ required: true, validator: checkID, trigger: "blur" }],
  takeMobile: [{ required: true, validator: checkPhoneNumber, trigger: "blur" }],
  takeAddress: [{ required: true, validator: isAddressDetailed, trigger: "blur" }],

  team: [{ required: true, trigger: "blur", message: "请选择团队" }],
  dataRule: [{ required: true, trigger: "blur", message: "请选择规则" }],
  dataState: [{ required: false, trigger: "blur", message: "请选择状态" }]
})
const handleAdd = () => {
  seeState.value = "add"
  dialogVisible.value = true
  const name1 = userStore.nickName ? userStore.username : userStore.nickName
  formData.source = userStore.teamName ? userStore.teamName : name1
}

// 生成报表
const handleCreateData = () => {
  seeState.value = "data"
  dialogVisible.value = true
  roleId.value = -1
}
//生成报表
const creatData = async () => {
  const dataTeamList = formData.teamList
  if (dataTeamList.length == 0) {
    ElMessage.error("请选团队")
    return
  }
  const legend = []
  for (let x = 0; x < dataTeamList.length; x++) {
    for (let i = 0; i < teamList.value.length; i++) {
      if (teamList.value[i].id === dataTeamList[x]) {
        legend.push(teamList.value[i].name)
      }
    }
  }

  const dataSeries = []

  switch (roleId.value) {
    case 0: {
      const start = new Date(formData.dayDate[0])
      const end = new Date(formData.dayDate[1])
      const timeList = dateUtil.getTimeTwo(
        dateUtil.dateFormat(start, "YYYY-MM-DD"),
        dateUtil.dateFormat(end, "YYYY-MM-DD")
      )
      const timeList2 = []
      for (let i = 0; i < timeList.length; i++) {
        const date = new Date(timeList[i])
        timeList2.push(dateUtil.dateFormat(date, "MM-DD"))
      }

      for (let i = 0; i < legend.length; i++) {
        const seriesData = ref<any>([])
        for (let x = 0; x < timeList.length; x++) {
          const time = new Date(timeList[x])
          await getCreateData(legend[i], time, time).then((res) => {
            seriesData.value.push(res)
          })
        }
        dataSeries.push({
          name: legend[i],
          type: "line",
          data: seriesData.value,
          itemStyle: { normal: { label: { show: true } } }
        })
      }
      if (!chartRun(timeList2, legend, dataSeries)) return
      break
    }

    case 1: {
      const start = new Date(formData.startWeekDate)
      const end = new Date(formData.endWeekDate)
      end.setDate(end.getDate() + 6)
      if (start > end) {
        ElMessage.error("开始日期不能大于结束日期")
        return
      }
      const timeList = dateUtil.getTimeTwo(
        dateUtil.dateFormat(start, "YYYY-MM-DD"),
        dateUtil.dateFormat(end, "YYYY-MM-DD")
      )
      const weekList = []
      for (let i = 0; i < timeList.length; i += 7) {
        weekList.push(new Date(timeList[i]))
      }

      for (let i = 0; i < legend.length; i++) {
        const seriesData = ref<any>([])
        for (let x = 0; x < weekList.length; x++) {
          const timeStart = new Date(weekList[x])
          const timeEnd = new Date(weekList[x])
          timeEnd.setDate(timeEnd.getDate() + 6)
          await getCreateData(legend[i], timeStart, timeEnd).then((res) => {
            seriesData.value.push(res)
          })
        }
        dataSeries.push({
          name: legend[i],
          type: "line",
          data: seriesData.value,
          itemStyle: { normal: { label: { show: true } } }
        })
      }
      for (let x = 0; x < weekList.length; x++) {
        weekList[x] = dateUtil.dateFormat(weekList[x], "ww周")
      }
      if (!chartRun(weekList, legend, dataSeries)) return
      break
    }

    case 2: {
      const year = new Date().getFullYear()
      const monthList = []
      for (let x = 0; x < legend.length; x++) {
        const seriesData = ref<any>([])
        for (let i = 0; i < 12; i++) {
          const month = new Date(year, i, 1)
          const endMonth = new Date(year, i + 1, 0)
          monthList[i] = dateUtil.dateFormat(month, "MM月")

          await getCreateData(legend[x], month, endMonth).then((res) => {
            seriesData.value.push(res)
          })
        }
        dataSeries.push({
          name: legend[x],
          type: "line",
          data: seriesData.value,
          itemStyle: { normal: { label: { show: true } } }
        })
      }

      if (!chartRun(monthList, legend, dataSeries)) return
      break
    }
    default:
      ElMessage.error("请选规则")
      return
  }
  seeState.value = "dataShow"
  dialogVisible.value = true
}

const getCreateData = async (source: string, start: Date, end: Date) => {
  const num = ref<number>(0)
  await getOrderDataApi({
    page: 1,
    size: 1000000,
    source: source,
    start: start.getTime() || "",
    end: end.getTime() || "",
    state: formData.orderState == null || formData.orderState == "" ? 0 : formData.orderState
  }).then((res) => {
    num.value = res.data.total
  })
  return num.value
}

const handleCreate = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      formData.chargingDate = new Date(payDate.value)
      uploadFuc()
    } else {
      return false
    }
  })
}
const resetForm = () => {
  currentUpdateId.value = undefined
  zctj.value = ""
  clearValidate()
  formData.orderId = ""
  formData.handleMobile = ""
  formData.sku = ""
  formData.cardName = ""
  formData.cardId = ""
  formData.consignee = ""
  formData.takeMobile = ""
  formData.takeAddress = ""
  formData.cardFront = ""
  formData.cardBack = ""
  formData.photo = ""
  formData.chargingState = ""
  formData.chargingDate = new Date(payDate.value)
  formData.result = ""
  formData.logisticsCompany = ""
  formData.logisticsId = ""
  formData.commissionState = ""
  formData.teamList = []
  formData.dataRole = ""
  formData.dayDate = ""
  formData.startWeekDate = ""
  formData.endWeekDate = ""
  formData.orderState = ""
  formData.activeData = ""
  formData.salesman = ""
  formData.remark = ""
  fileList0.value = []
  fileList1.value = []
  fileList2.value = []
  isCard.value = false
  maxAge.value = 0
  minAge.value = 0
  isNoArea.value = ""
  comboStr.value = ""
  // selectedOptions.value = []
}
//#endregion

//#endregion

// row数据公用
const rowData = (row: any) => {
  currentUpdateId.value = row.id
  formData.orderId = row.orderId
  formData.source = row.source
  formData.iccid = row.iccid
  formData.handleMobile = row.handleMobile
  formData.sku = row.sku
  comboSkuToStr(row)
  formData.cardName = row.cardName
  formData.cardId = row.cardId
  formData.consignee = row.consignee
  formData.takeMobile = row.takeMobile
  formData.takeAddress = row.takeAddress
  formData.note = row.note
  formData.chargingState = row.chargingState
  payDate.value = row.chargingDate
  formData.result = row.result
  formData.recorder = row?.recorder
  formData.salesman = row?.salesman
  formData.remark = row?.remark
  formData.activeData = row?.activeData
  formData.logisticsCompany = row.logisticsCompany
  formData.logisticsId = row.logisticsId
  formData.commissionState = row.commissionState
  if (row.cardFront) {
    fileList0.value = row.cardFront?.split(",").map((item: any) => {
      return {
        url: item
      }
    })
  } else {
    fileList0.value = []
  }

  // console.log(fileList0.value, 999)

  if (row.cardBack) {
    fileList1.value = row.cardBack?.split(",").map((item: any) => {
      return {
        url: item
      }
    })
  } else {
    fileList1.value = []
  }
  if (row.photo) {
    fileList2.value = row.photo?.split(",").map((item: any) => {
      return {
        url: item
      }
    })
  } else {
    fileList2.value = []
  }

  formData.cardBack = row.cardBack?.split("/image/")[1]
  formData.cardFront = row.cardFront?.split("/image/")[1]
  formData.photo = row.photo?.split("/image/")[1]
  dialogVisible.value = true
}

//#region 改
// 重新提交改
const currentUpdateId = ref<undefined | string>(undefined)
const handleUpdate = (row: IGetOrderData) => {
  seeState.value = "update"
  loading.value = true
  getOrderOneApi({
    id: row.id
  }).then((res: any) => {
    rowData(res.data)
    loading.value = false
  })
}
// 再次提交改
const zctj = ref("")
const handleUpdateZc = (row: IGetOrderData) => {
  seeState.value = "update"
  zctj.value = "zctj"
  loading.value = true
  getOrderOneApi({
    id: row.id
  }).then((res: any) => {
    console.log(res, "再次提交改")
    rowData(res.data)
    loading.value = false
  })
}
const handleCreateZc = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      formData.chargingDate = new Date(payDate.value)
      uploadFucZc()
    } else {
      return false
    }
  })
}
//#endregion

//#region 查
const tableData = ref<IGetOrderData[]>([])
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive({
  source: "小程序",
  department: userStore.department,
  sku: "",
  cardName: "",
  orderOutId: "",
  handleMobile: "",
  cardId: "",
  takeMobile: "",
  searchDate: "",
  start: "",
  end: "",
  state: "",
  id: "",
  salesman: "",
  superName: "",
  re_id: ""
})

const getTableData = () => {
  getTableInfo(false)
}
/**方便下载订单功能将请求单拎出来 */
const getTableInfo = async (isDown: boolean) => {
  loading.value = true
  const page = ref<number>(paginationData.currentPage)
  const size = ref<number>(paginationData.pageSize)
  if (isDown) {
    page.value = 1
    if (userStore.teamName) {
      size.value = 1000
    } else {
      size.value = 10000000
    }
  } else {
    page.value = paginationData.currentPage
    size.value = paginationData.pageSize
  }
  const salesman = ref<string>(searchData.salesman)
  if (salesman.value !== "") {
    salesman.value = searchData.salesman
      .split(",")
      .map((item: any) => {
        return "'" + item + "'"
      })
      .join(",")
  } else {
    salesman.value = ""
  }
  await getOrderDataApi({
    page: page.value,
    size: size.value,
    source: searchData.source,
    department: searchData.department,
    cardName: searchData.cardName,
    orderOutId: searchData.orderOutId,
    handleMobile: searchData.handleMobile,
    cardId: searchData.cardId,
    takeMobile: searchData.takeMobile,
    sku: searchData.sku,
    start: new Date(searchData?.searchDate[0]).getTime() || "",
    end: new Date(searchData?.searchDate[1]).getTime() || "",
    state: searchData.state || 0,
    id: searchData.id,
    superName: searchData.superName,
    salesman: salesman.value,
    re_id: searchData.re_id
  })
    .then((res) => {
      paginationData.total = res.data.total
      tableData.value = res.data.orderList
      console.log(tableData.value, "订单详情")
    })
    .catch(() => {
      tableData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
const handleSearch = () => {
  if (paginationData.currentPage === 1) {
    getTableData()
  }
  paginationData.currentPage = 1
}
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  if (paginationData.currentPage === 1) {
    getTableData()
  }
  paginationData.currentPage = 1
}
const handleRefresh = () => {
  getTableData()
}

/**查看 详情 */

const handleSeeMore = (row: any) => {
  loading.value = true
  seeState.value = "see"
  getOrderOneApi({
    id: row.id
  }).then((res: any) => {
    rowData(res.data)
    loading.value = false
  })
}
//#endregion

//规则切换
const roleId = ref<number>(-1)
const roleChange = (val: any) => {
  if (val >= 0) {
    roleId.value = val
  } else {
    roleId.value = 0
  }
}

/**  套餐切换 */
const isCard = ref<boolean>(false)
const maxAge = ref<number>(0)
const minAge = ref<number>(0)
const isNoArea = ref<any>("")
const noAreaFinallyArry = ref<any>([]) //不发货 省市区
const noAreaP = ref<any>([]) //不发货省
const noAreaPandC = ref<any>([]) //不发货省市
const noField = ref<any>([]) //敏感词
const comboChange = (val: any) => {
  // console.log(val)
  if (val) {
    const filterCombo = ref<any>(comboList.value.filter((item: any) => item.id + "" === val))
    isCard.value = filterCombo.value[0]?.card
    maxAge.value = filterCombo.value[0]?.maxAge
    minAge.value = filterCombo.value[0]?.minAge
    isNoArea.value = filterCombo.value[0]?.area
    noField.value = filterCombo.value[0]?.guide
    if (isNoArea.value) {
      const arr = JSON.parse(isNoArea.value.replace(/'/g, '"'))
      noAreaP.value = arr.filter((item: any) => item.length == 1).flat()
      noAreaPandC.value = arr.filter((item: any) => item.length == 2).map((item: any) => item.join(""))
      noAreaFinallyArry.value = arr.filter((item: any) => item.length == 3).map((item: any) => item.join(""))
    }
  } else {
    isCard.value = false
    maxAge.value = 60
    minAge.value = 16
    isNoArea.value = ""
  }
}

/** 图片改变 */
const handleChageImg = (file: any, resfileList: any) => {
  const size = ref(2)
  const fileSizeFlag = file.size / 1024 / 1024 < size.value
  if (!fileSizeFlag) {
    ElMessage.error(`请上传不大于${size.value}M的图片!`)
    fileList0.value = []
  } else {
    fileList0.value = resfileList
  }
}
const handleChageImg1 = (file: any, resfileList: any) => {
  const size = ref(2)
  const fileSizeFlag = file.size / 1024 / 1024 < size.value
  if (!fileSizeFlag) {
    ElMessage.error(`请上传不大于${size.value}M的图片!`)
    fileList1.value = []
  } else {
    fileList1.value = resfileList
  }
}
const handleChageImg2 = (file: any, resfileList: any) => {
  const size = ref(2)
  const fileSizeFlag = file.size / 1024 / 1024 < size.value
  if (!fileSizeFlag) {
    ElMessage.error(`请上传不大于${size.value}M的图片!`)
    fileList2.value = []
  } else {
    fileList2.value = resfileList
  }
}
// 移除图片
const handleRemove = (file: any) => {
  const list = fileList0.value
  for (const i in list) {
    if (list[i].uid === file.uid) {
      list.splice(i, 1)
    }
  }
  fileList0.value = list
}
// 移除图片
const handleRemove1 = (file: any) => {
  const list = fileList1.value
  for (const i in list) {
    if (list[i].uid === file.uid) {
      list.splice(i, 1)
    }
  }
  fileList1.value = list
}
// 移除图片
const handleRemove2 = (file: any) => {
  const list = fileList2.value
  for (const i in list) {
    if (list[i].uid === file.uid) {
      list.splice(i, 1)
    }
  }
  fileList2.value = list
}

// 预览图片
const dialogImageUrl = ref("") /**预览url  */
const dialogVisible1 = ref(false) /**预览弹窗 */
const handlePictureCardPreview = (file: any) => {
  dialogImageUrl.value = file.url
  dialogVisible1.value = true
}

//检测下单用户是否存在高危

const checkRisk = (val: any) => {
  // console.log(val.target.value, "asd")
  const cid = val.target.value
  if (cid) {
    getRiskByCardIdApi({
      risk_card_id: cid
    }).then((res: any) => {
      console.log(res)
      if (res.code == 200 && res.data) {
        if (res.data.risk_level == 0) {
          ElMessage.warning("检测到此用户风险等级为高危用户！")
          setTimeout(() => {
            formData.cardId = ""
          }, 1000)
        }
        if (res.data.risk_level == 1) {
          ElMessage.warning("检测到此用户风险等级为中危用户！")
        }
        if (res.data.risk_level == 2) {
          ElMessage.warning("检测到此用户风险等级为低危用户！")
        }
      }
    })
  }
}

//  确定上传
const uploadFuc = async () => {
  // console.log(fileList0.value)
  loading.value = true
  if ((fileList0.value.length === 0 || fileList1.value.length === 0 || fileList2.value.length === 0) && isCard.value) {
    ElMessage.error("请上传相关照片")
    loading.value = false
    return
  }
  const fileData = new FormData()
  const fileData1 = new FormData()
  const fileData2 = new FormData()
  fileList0.value.forEach((file: any) => {
    fileData.append("file", file.raw)
    fileData.append("name", formData.cardName)
  })
  fileList1.value.forEach((file: any) => {
    fileData1.append("file", file.raw)
    fileData1.append("name", formData.cardName)
  })
  fileList2.value.forEach((file: any) => {
    fileData2.append("file", file.raw)
    fileData2.append("name", formData.cardName)
  })
  const currentAge = Number(IdCard(formData.cardId, 3))
  if (currentAge >= minAge.value && currentAge <= maxAge.value) {
    console.log("年龄核检通过")
  } else {
    ElMessage.error(`年龄限制为${minAge.value}-${maxAge.value}周岁，请核对身份证信息是否正确！`)
    loading.value = false
    return
  }
  if (isCard.value) {
    if (fileList0.value[0].status === "ready") {
      await uploadCidImageList(fileData).then((res: any) => {
        if (res.code == 200) {
          formData.cardFront = res.data.split("/image/")[1]
          fileList0.value = []
        }
      })
    }
    if (fileList1.value[0].status === "ready") {
      await uploadCidImageList(fileData1).then((res: any) => {
        if (res.code == 200) {
          formData.cardBack = res.data.split("/image/")[1]
          fileList1.value = []
        }
      })
    }
    if (fileList2.value[0].status === "ready") {
      await uploadCidImageList(fileData2).then((res: any) => {
        if (res.code == 200) {
          formData.photo = res.data.split("/image/")[1]
          fileList2.value = []
        }
      })
    }
  }
  const inputArea = formData.takeAddress.trim().split(" ")
  /**不发货省 */
  if (noAreaP.value.length) {
    if (noAreaP.value.includes(inputArea[0])) {
      ElMessage.warning("填写的地址有误或在不发货地区喔！^-^")
      loading.value = false
      return
    }
  }
  /**不发货省市 */
  // console.log(noAreaPandC.value)
  if (noAreaPandC.value.length) {
    if (noAreaPandC.value.includes(`${inputArea[0]}${inputArea[1]}`)) {
      ElMessage.warning("填写的地址有误或在不发货地区喔！^-^")
      loading.value = false
      return
    }
  }
  /**不发货省市区 */
  // console.log(noAreaFinallyArry.value)

  if (noAreaFinallyArry.value.length) {
    if (noAreaFinallyArry.value.includes(`${inputArea[0]}${inputArea[1]}${inputArea[2]}`)) {
      ElMessage.warning("填写的地址有误或在不发货地区喔！^-^")
      loading.value = false
      return
    }
  }
  if (noField.value) {
    const regex = new RegExp(noField.value.split(",").join("|"))
    if (regex.test(formData.takeAddress)) {
      ElMessage.warning("填写的地址含有敏感词！^-^")
      loading.value = false
      return
    }
  }

  if (currentUpdateId.value === undefined) {
    await createOrderDataApi(
      {
        orderId: formData.orderId,
        source: formData.source,
        handleMobile: formData.handleMobile,
        sku: formData.sku,
        cardName: formData.cardName,
        cardId: formData.cardId,
        consignee: formData.consignee,
        takeMobile: formData.takeMobile,
        takeAddress: formData.takeAddress,
        cardFront: formData.cardFront,
        cardBack: formData.cardBack,
        photo: formData.photo,
        salesman: formData.salesman,
        remark: formData.remark,
        chargingState: formData.chargingState,
        chargingDate: formData.chargingDate,
        result: formData.result,
        logisticsCompany: formData.logisticsCompany,
        logisticsId: formData.logisticsId,
        commissionState: formData.commissionState
      },
      userStore.usernameID,
      false
    )
      .then(() => {
        ElMessage.success("新增成功")
        dialogVisible.value = false
        getTableData()
      })
      .finally(() => {
        loading.value = false
      })
  } else {
    await updateOrderDataApi({
      id: currentUpdateId.value,
      orderId: formData.orderId,
      source: formData.source,
      iccid: formData.iccid,
      handleMobile: formData.handleMobile,
      sku: formData.sku,
      cardName: formData.cardName,
      cardId: formData.cardId,
      consignee: formData.consignee,
      takeMobile: formData.takeMobile,
      takeAddress: formData.takeAddress,
      note: formData.note,
      cardFront: formData.cardFront,
      cardBack: formData.cardBack,
      photo: formData.photo,
      salesman: formData.salesman,
      remark: formData.remark,
      activeData: formData.activeData,
      chargingState: formData.chargingState,
      chargingDate: formData.chargingDate,
      result: formData.result,
      logisticsCompany: formData.logisticsCompany,
      logisticsId: formData.logisticsId,
      commissionState: formData.commissionState,
      update: formData.update
    })
      .then(() => {
        ElMessage.success("修改成功")
        dialogVisible.value = false
        getTableData()
      })
      .finally(() => {
        loading.value = false
      })
  }
}
//  确定再次上传
const uploadFucZc = async () => {
  // console.log(fileList0.value)
  loading.value = true
  if ((fileList0.value.length === 0 || fileList1.value.length === 0 || fileList2.value.length === 0) && isCard.value) {
    ElMessage.error("请上传相关照片")
    loading.value = false
    return
  }
  const fileData = new FormData()
  const fileData1 = new FormData()
  const fileData2 = new FormData()
  fileList0.value.forEach((file: any) => {
    fileData.append("file", file.raw)
    fileData.append("name", formData.cardName)
  })
  fileList1.value.forEach((file: any) => {
    fileData1.append("file", file.raw)
    fileData1.append("name", formData.cardName)
  })
  fileList2.value.forEach((file: any) => {
    fileData2.append("file", file.raw)
    fileData2.append("name", formData.cardName)
  })
  const currentAge = Number(IdCard(formData.cardId, 3))
  if (currentAge >= minAge.value && currentAge <= maxAge.value) {
    console.log("年龄核检通过")
  } else {
    ElMessage.error(`年龄限制为${minAge.value}-${maxAge.value}周岁，请核对身份证信息是否正确！`)
    loading.value = false
    return
  }
  if (isCard.value) {
    if (fileList0.value[0].status === "ready") {
      await uploadCidImageList(fileData).then((res: any) => {
        if (res.code == 200) {
          formData.cardFront = res.data.split("/image/")[1]
          fileList0.value = []
        }
      })
    }
    if (fileList1.value[0].status === "ready") {
      await uploadCidImageList(fileData1).then((res: any) => {
        if (res.code == 200) {
          formData.cardBack = res.data.split("/image/")[1]
          fileList1.value = []
        }
      })
    }
    if (fileList2.value[0].status === "ready") {
      await uploadCidImageList(fileData2).then((res: any) => {
        if (res.code == 200) {
          formData.photo = res.data.split("/image/")[1]
          fileList2.value = []
        }
      })
    }
  }
  const inputArea = formData.takeAddress.trim().split(" ")
  /**不发货省 */
  if (noAreaP.value.length) {
    if (noAreaP.value.includes(inputArea[0])) {
      ElMessage.warning("填写的地址有误或在不发货地区喔！^-^")
      loading.value = false
      return
    }
  }
  /**不发货省市 */
  // console.log(noAreaPandC.value)
  if (noAreaPandC.value.length) {
    if (noAreaPandC.value.includes(`${inputArea[0]}${inputArea[1]}`)) {
      ElMessage.warning("填写的地址有误或在不发货地区喔！^-^")
      loading.value = false
      return
    }
  }
  /**不发货省市区 */
  // console.log(noAreaFinallyArry.value)

  if (noAreaFinallyArry.value.length) {
    if (noAreaFinallyArry.value.includes(`${inputArea[0]}${inputArea[1]}${inputArea[2]}`)) {
      ElMessage.warning("填写的地址有误或在不发货地区喔！^-^")
      loading.value = false
      return
    }
  }
  if (noField.value) {
    const regex = new RegExp(noField.value.split(",").join("|"))
    if (regex.test(formData.takeAddress)) {
      ElMessage.warning("填写的地址含有敏感词！^-^")
      loading.value = false
      return
    }
  }

  if (currentUpdateId.value === undefined) {
    console.log(1)
  } else {
    await updateOrderDataApiZc({
      id: currentUpdateId.value,
      orderId: formData.orderId,
      source: formData.source,
      iccid: formData.iccid,
      handleMobile: formData.handleMobile,
      sku: formData.sku,
      cardName: formData.cardName,
      cardId: formData.cardId,
      consignee: formData.consignee,
      takeMobile: formData.takeMobile,
      takeAddress: formData.takeAddress,
      note: formData.note,
      cardFront: formData.cardFront,
      cardBack: formData.cardBack,
      photo: formData.photo,
      salesman: formData.salesman,
      remark: formData.remark,
      activeData: formData.activeData,
      chargingState: formData.chargingState,
      chargingDate: formData.chargingDate,
      result: formData.result,
      logisticsCompany: formData.logisticsCompany,
      logisticsId: formData.logisticsId,
      commissionState: formData.commissionState,
      update: formData.update
    })
      .then(() => {
        ElMessage.success("修改成功")
        dialogVisible.value = false
        getTableData()
      })
      .finally(() => {
        loading.value = false
      })
  }
}
/** 订单下载 默认下载所有数据，查询后下载所有符合查询条件的数据*/
const dialogVisible3 = ref<boolean>(false)
const formData1 = reactive<any>({
  download: ""
})
const resetForm1 = () => {
  formData1.download = ""
}
const formRules1: FormRules = reactive({
  download: [{ required: true, trigger: "blur", message: "请输入密码" }]
})
const downLoad = async () => {
  dialogVisible3.value = true
}

const handleDownLoad = () => {
  const salesman1 = ref<string>(searchData.salesman)
  if (salesman1.value !== "") {
    salesman1.value = searchData.salesman
      .split(",")
      .map((item: any) => {
        return "'" + item + "'"
      })
      .join(",")
  } else {
    salesman1.value = ""
  }
  const basePW = commonStore.DOWNLOADWORD
  if (formData1.download !== basePW) {
    ElMessage.error("密码错误，请重新输入！")
    formData1.download = ""
  } else {
    loading.value = true
    downLoadOrderTable({
      source: searchData.source,
      department: searchData.department,
      cardName: searchData.cardName,
      orderOutId: searchData.orderOutId,
      handleMobile: searchData.handleMobile,
      cardId: searchData.cardId,
      takeMobile: searchData.takeMobile,
      sku: searchData.sku,
      start: new Date(searchData?.searchDate[0]).getTime() || "",
      end: new Date(searchData?.searchDate[1]).getTime() || "",
      state: searchData.state || 0,
      id: searchData.id,
      superName: searchData.superName,
      salesman: salesman1.value
    })
      .then((res: any) => {
        const blob = new Blob([res.data], {
          type: "application/xlsx;charset=utf-8"
        })
        // console.log(res)
        const downloadElement = document.createElement("a")
        const href = window.URL.createObjectURL(blob)
        downloadElement.href = href
        downloadElement.download = "订单.xlsx"
        document.body.appendChild(downloadElement)
        downloadElement.click()
        window.URL.revokeObjectURL(href)
        // if (res.data.code == 200) {
        // ElMessage.success("下载已经进入队列")
        dialogVisible3.value = false
        formData1.download = ""
        // }
      })
      .finally(() => {
        loading.value = false
      })
  }
}
/** 订单下载 END*/

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })
/** 监听套餐数据是否变化 */
watch([() => formData.sku], (newValue) => comboChange(newValue.join()))
/**监听套餐缓存(pinia) */
comboStore.getComoboFn()
const comboList1 = ref<any>([])
watch(
  [() => comboStore.comboListStore],
  (newValue) => {
    comboList.value = newValue.flat()
    comboList1.value = newValue.flat().filter((item) => item.state === "true")
  },
  {
    immediate: true
  }
)
/**E N D */

/**监听代理账号缓存(pinia) */
import { useReStore } from "@/store/modules/reId"
const reStore = useReStore()
reStore.getReFn()
const reList = ref<any>([])
watch(
  [() => reStore.reListStore],
  (newValue) => {
    reList.value = newValue.flat()
  },
  {
    immediate: true
  }
)
/**E N D */

// ** 清除规则报错信息
const clearValidate = () => {
  formRef.value?.clearValidate()
}
const defaultTime1: [Date, Date] = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)]
</script>

<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="id" label="订单ID">
          <el-input v-model.trim="searchData.id" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="orderOutId" label="订单外部ID">
          <el-input v-model.trim="searchData.orderOutId" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="cardName" label="身份证名字">
          <el-input v-model.trim="searchData.cardName" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="cardId" label="身份证号">
          <el-input v-model.trim="searchData.cardId" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="handleMobile" label="办理手机号">
          <el-input v-model.trim="searchData.handleMobile" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="takeMobile" label="收件电话">
          <el-input v-model.trim="searchData.takeMobile" placeholder="请输入" />
        </el-form-item>
        <!-- <el-form-item prop="source" label="订单来源" v-if="!userStore.teamName">
          <el-input v-model="searchData.source" placeholder="请输入" />
        </el-form-item> -->
        <!-- <el-form-item prop="superName" label="上级名" v-if="!userStore.teamName">
          <el-input v-model="searchData.superName" placeholder="请输入" />
        </el-form-item> -->
        <el-form-item prop="salesman" label="发展业务员">
          <el-input v-model.trim="searchData.salesman" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="re_id" label="推荐人">
          <el-select v-model="searchData.re_id" clearable filterable placeholder="请选推荐人" style="width: 240px">
            <el-option v-for="item in reList" :key="item.user_id" :label="item.user_name" :value="item.user_id" />
          </el-select>
        </el-form-item>
        <el-form-item prop="sku" label="套餐">
          <el-select v-model="searchData.sku" clearable filterable placeholder="请选套餐" style="width: 240px">
            <el-option v-for="item in comboList" :key="item.id" :label="item.name" :value="item.id + ''" />
          </el-select>
        </el-form-item>
        <el-form-item prop="state" label="状态">
          <el-select v-model="searchData.state" clearable placeholder="请选择" style="width: 240px">
            <el-option v-for="item in codeList" :key="item.code" :label="item.state" :value="item.code" />
          </el-select>
        </el-form-item>
        <el-form-item prop="searchDate" label="订单日期">
          <el-date-picker
            v-model="searchData.searchDate"
            type="datetimerange"
            unlink-panels
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :shortcuts="shortcuts"
            :size="size"
            :default-time="defaultTime1"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <div style="display: none">
          <el-button type="primary" :icon="CirclePlus" @click="handleAdd">添加订单</el-button>
          <!-- <el-button type="danger" :icon="UploadFilled">批量上传</el-button> -->
          <el-upload
            ref="upload"
            class="upload-demo"
            action="api/order/upload"
            :limit="1"
            :headers="uploadheaders"
            :on-exceed="handleExceed"
            :on-success="handleSucc"
            :auto-upload="false"
            style="display: inline-block; vertical-align: top; margin-left: 10px"
          >
            <template #trigger>
              <el-button type="danger" :icon="Folder">选择文件</el-button>
            </template>
            <el-button
              style="vertical-align: top"
              class="ml-3"
              type="success"
              :icon="UploadFilled"
              @click="submitUpload"
            >
              批量上传
            </el-button>
          </el-upload>
          <!-- <el-link type="primary" :icon="Download" style="margin-left: 50px" href="api/order/down/downTemplate" Download
            >下载模版</el-link
          > -->
        </div>
        <div>
          <el-button type="primary" :icon="Download" @click="handleCreateData" style="display: none"
            >生成报表</el-button
          >
          <el-tooltip content="下载">
            <el-button type="primary" :icon="Download" circle @click="downLoad" />
          </el-tooltip>
          <el-tooltip content="刷新表格">
            <el-button type="primary" :icon="RefreshRight" circle @click="handleRefresh" />
          </el-tooltip>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table :data="tableData">
          <!-- <el-table-column type="selection" width="50" align="center" /> -->
          <el-table-column prop="id" label="ID" align="center" />
          <el-table-column prop="orderId" label="外部ID" align="center" />
          <el-table-column prop="create" label="创建时间" align="center">
            <template #default="scope">
              {{ formatDateTime(scope.row.create) }}
            </template>
          </el-table-column>
          <el-table-column prop="update" label="反馈时间" align="center">
            <template #default="scope">
              {{ formatDateTime(scope.row.update) }}
            </template>
          </el-table-column>
          <el-table-column prop="source" label="订单来源" align="center" />
          <el-table-column prop="reName" label="推荐人" align="center" />
          <el-table-column prop="sku" label="套餐" align="center" :formatter="formatterCombo" width="220" />
          <el-table-column prop="handleMobile" label="入网号" align="center" />
          <!-- <el-table-column prop="iccid" label="ICCID" align="center" /> -->
          <el-table-column prop="cardName" label="姓名" align="center" />
          <el-table-column prop="cardId" label="身份证号" align="center" />
          <el-table-column prop="consignee" label="收货人" align="center" />
          <el-table-column prop="takeMobile" label="收货电话" align="center" />
          <el-table-column prop="takeAddress" label="收货地址" align="center" show-overflow-tooltip />
          <el-table-column label="订单状态" align="center">
            <template #default="scope">
              <div
                :class="{
                  doing: scope.row.state.code <= 200 && scope.row.state.code > 199,
                  success: scope.row.state.code >= 100 && scope.row.state.code < 200,
                  error: scope.row.state.code >= 400,
                  again: scope.row.state.code < 0
                }"
              >
                {{ scope.row.state.state }}
                <div class="text-ellipsis" v-if="scope.row.result" style="font-size: 12px">
                  <el-tooltip placement="top">
                    <template #content> {{ scope.row.result }} </template>
                    <span style="cursor: pointer">({{ scope.row.result }})</span>
                  </el-tooltip>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="物流状态" align="center" show-overflow-tooltip>
            <template #default="scope">
              {{ scope.row.logisticsState.str }}
            </template>
          </el-table-column>
          <el-table-column prop="chargingState" label="充值情况" align="center" show-overflow-tooltip />
          <el-table-column prop="re_super" label="推荐人(上级)" align="center" v-if="!userStore.teamName" />
          <el-table-column prop="re_upup" label="推荐人(上上级)" align="center" v-if="!userStore.teamName" />
          <el-table-column prop="superiorName" label="上级名" align="center" v-if="!userStore.teamName" />
          <el-table-column fixed="right" label="操作" width="100" align="center">
            <template #default="scope">
              <el-button
                type="primary"
                text
                bg
                size="small"
                @click="handleUpdate(scope.row)"
                :disabled="scope.row.state.code < 400"
                >重新提交</el-button
              >
              <br />
              <el-button
                v-if="scope.row.state.code == 402"
                type="primary"
                text
                bg
                size="small"
                @click="handleUpdateZc(scope.row)"
                >再次提交</el-button
              ><br />
              <el-button type="primary" text bg size="small" @click="handleSeeMore(scope.row)"> 查看详情</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 新增/修改 -->
    <el-dialog
      v-model="dialogVisible"
      :title="seeState === 'see' ? '查看详情' : currentUpdateId === undefined ? '新增订单' : '修改订单'"
      @close="resetForm"
      width="80%"
      v-if="seeState !== 'data' && seeState !== 'dataShow'"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" label-position="left">
        <el-form-item prop="orderId" label="订单外部ID" v-if="zctj !== 'zctj'">
          <el-input v-model="formData.orderId" placeholder="请输入" :disabled="seeState === 'see'" />
        </el-form-item>
        <el-form-item prop="source" label="订单来源">
          <el-input v-model="formData.source" placeholder="请输入" disabled />
        </el-form-item>
        <el-form-item prop="recorder" label="录单员" v-if="seeState === 'see'">
          <el-input v-model="formData.recorder" placeholder="请输入" disabled />
        </el-form-item>
        <el-form-item prop="recorder" label="发展业务员" v-if="zctj !== 'zctj'">
          <el-input v-model="formData.salesman" placeholder="请输入" :disabled="seeState === 'see'" />
        </el-form-item>
        <el-form-item prop="recorder" label="备注" v-if="zctj !== 'zctj'">
          <el-input v-model="formData.remark" placeholder="请输入" :disabled="seeState === 'see'" />
        </el-form-item>
        <el-form-item prop="state" label="状态" v-if="seeState === 'see' && zctj !== 'zctj'">
          <!-- <el-input v-model="searchData.sku" placeholder="请输入" /> -->
          <el-select
            v-model="formData.state"
            clearable
            placeholder="请选择"
            style="width: 240px"
            :disabled="seeState === 'see'"
          >
            <el-option v-for="item in codeList" :key="item.code" :label="item.state" :value="item.code" />
          </el-select>
        </el-form-item>
        <el-form-item prop="sku" label="订购的套餐">
          <el-input type="textarea" disabled v-if="seeState === 'see'" v-model="comboStr" />
          <el-select
            v-else
            v-model="formData.sku"
            clearable
            filterable
            placeholder="请选套餐,可输入快速查询"
            style="width: 100%"
            @change="comboChange"
          >
            <!-- :value="item.id + ''" -->
            <el-option
              v-for="item in comboList1"
              :key="item.id"
              :label="item.name"
              :value="String(item.id)"
              :disabled="item.state === 'false'"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="handleMobile" label="办理手机号" v-if="seeState === 'see'">
          <el-input
            v-model="formData.handleMobile"
            :disabled="seeState === 'see'"
            placeholder="请输入"
            maxlength="11"
            show-word-limit
          />
        </el-form-item>
        <el-form-item prop="iccid" label="ICCID" v-if="seeState === 'see'">
          <el-input v-model="formData.iccid" :disabled="seeState === 'see'" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="cardName" label="身份证姓名">
          <el-input v-model="formData.cardName" :disabled="seeState === 'see'" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="cardId" label="身份证号">
          <el-input
            v-model="formData.cardId"
            :disabled="seeState === 'see'"
            placeholder="请输入"
            maxlength="18"
            show-word-limit
            @blur="checkRisk"
          />
        </el-form-item>
        <el-form-item prop="chargingState" label="充值情况" v-if="seeState === 'see'">
          <el-input
            autosize
            type="textarea"
            :disabled="seeState === 'see'"
            v-model="formData.chargingState"
            placeholder="请输入"
          />
        </el-form-item>
        <el-form-item prop="chargingDate" label="充值时间" v-if="seeState === 'see'">
          <el-date-picker v-model="payDate" :disabled="seeState === 'see'" type="datetime" placeholder="请选择时间" />
        </el-form-item>
        <el-form-item prop="result" label="结果描述" v-if="seeState === 'see'">
          <el-input
            v-model="formData.result"
            :disabled="seeState === 'see'"
            autosize
            type="textarea"
            placeholder="请输入"
          />
        </el-form-item>
        <el-form-item prop="logisticsCompany" label="物流公司" v-if="seeState !== 'add' && zctj !== 'zctj'">
          <el-input v-model="formData.logisticsCompany" :disabled="seeState === 'see'" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="logisticsId" label="物流单号" v-if="seeState !== 'add' && zctj !== 'zctj'">
          <el-input v-model="formData.logisticsId" :disabled="seeState === 'see'" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="activeData" label="激活数据" v-if="seeState === 'see'">
          <el-input v-model="formData.activeData" type="textarea" placeholder="请输入" :disabled="seeState === 'see'" />
        </el-form-item>
        <el-form-item prop="kickback" label="结佣数据" v-if="seeState === 'see'">
          <el-input v-model="formData.kickback" type="textarea" placeholder="请输入" :disabled="seeState === 'see'" />
        </el-form-item>
        <el-form-item prop="commissionState" label="佣金状态" v-if="seeState === 'see'">
          <el-input
            v-model="formData.commissionState"
            :disabled="seeState === 'see'"
            type="textarea"
            autosize
            placeholder="请输入"
          />
        </el-form-item>
        <el-form-item prop="consignee" label="收货人">
          <el-input v-model="formData.consignee" :disabled="seeState === 'see'" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="takeMobile" label="收货电话">
          <el-input
            v-model="formData.takeMobile"
            :disabled="seeState === 'see'"
            placeholder="请输入"
            maxlength="11"
            show-word-limit
          />
        </el-form-item>
        <el-form-item prop="takeAddress">
          <template #label>
            <span>收货地址</span>
            <el-tooltip class="box-item" effect="customized" placement="bottom">
              <template #content>
                地址格式：某某省 某某市 某某区 详细地址<br />
                例如 河南省 焦作市 山阳区 某某小区某某楼503<br />
                格式不正确不予通过
              </template>
              <el-icon style="cursor: pointer"><InfoFilled /></el-icon>
            </el-tooltip>
          </template>
          <el-input
            v-model="formData.takeAddress"
            :disabled="seeState === 'see'"
            placeholder=" 地址格式：河南省 焦作市 山阳区 某某小区某某楼503"
          />
        </el-form-item>
        <el-form-item v-if="isCard || formData.cardFront" prop="cardFront" label="身份证正面照">
          <el-upload
            :auto-upload="false"
            :file-list="fileList0"
            :show-file-list="true"
            list-type="picture-card"
            :limit="1"
            accept="image/*"
            :on-change="handleChageImg"
            :disabled="fileList0.length !== 0"
          >
            <el-icon><Plus /></el-icon>
            <template #file="{ file }">
              <div>
                <img class="el-upload-list__item-thumbnail" :src="file.url" />
                <span class="el-upload-list__item-actions">
                  <span class="el-upload-list__item-delete" @click="handleRemove(file)" v-if="seeState !== 'see'">
                    <el-icon>
                      <Delete />
                    </el-icon>
                  </span>
                  <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                    <el-icon>
                      <zoom-in />
                    </el-icon>
                  </span>
                </span>
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item v-if="isCard || formData.cardBack" prop="cardBack" label="身份证反面照">
          <el-upload
            :auto-upload="false"
            :file-list="fileList1"
            :show-file-list="true"
            list-type="picture-card"
            :limit="1"
            accept="image/*"
            :on-change="handleChageImg1"
            :disabled="fileList1.length !== 0"
          >
            <el-icon><Plus /></el-icon>
            <template #file="{ file }">
              <div>
                <img class="el-upload-list__item-thumbnail" :src="file.url" />
                <span class="el-upload-list__item-actions">
                  <span class="el-upload-list__item-delete" @click="handleRemove1(file)" v-if="seeState !== 'see'">
                    <el-icon>
                      <Delete />
                    </el-icon>
                  </span>
                  <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                    <el-icon>
                      <zoom-in />
                    </el-icon>
                  </span>
                </span>
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item v-if="isCard || formData.photo" prop="photo" label="人像照片">
          <el-upload
            :auto-upload="false"
            :file-list="fileList2"
            :show-file-list="true"
            list-type="picture-card"
            :limit="1"
            accept="image/*"
            :on-change="handleChageImg2"
            :disabled="fileList2.length !== 0"
          >
            <el-icon><Plus /></el-icon>
            <template #file="{ file }">
              <div>
                <img class="el-upload-list__item-thumbnail" :src="file.url" />
                <span class="el-upload-list__item-actions">
                  <span class="el-upload-list__item-delete" @click="handleRemove2(file)" v-if="seeState !== 'see'">
                    <el-icon>
                      <Delete />
                    </el-icon>
                  </span>
                  <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                    <el-icon>
                      <zoom-in />
                    </el-icon>
                  </span>
                </span>
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false" v-if="seeState !== 'see'">取消</el-button>
        <el-button type="primary" @click="handleCreate" v-if="seeState !== 'see' && zctj !== 'zctj'" :disabled="loading"
          >确认</el-button
        >
        <el-button type="primary" @click="handleCreateZc" v-if="zctj == 'zctj'" :disabled="loading"
          >确认再次提交</el-button
        >
      </template>
    </el-dialog>
    <!-- 生成报表 -->
    <el-dialog v-model="dialogVisible" :title="'生成报表'" @close="resetForm" width="80%" v-else>
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" label-position="left">
        <el-form-item prop="team" label="报表团队">
          <el-select
            v-model="formData.teamList"
            clearable
            filterable
            multiple
            placeholder="请选团队,可输入快速查询"
            style="width: 240px"
          >
            <el-option v-for="item in teamList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item prop="dataRule" label="生成规则">
          <el-select
            v-model="formData.dataRole"
            clearable
            filterable
            placeholder="请选规则"
            style="width: 240px"
            @change="roleChange"
          >
            <el-option v-for="item in roleList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item prop="searchDate" label="选择日期" v-if="roleId === 0" class="date-box">
          <el-date-picker
            v-model="formData.dayDate"
            type="daterange"
            unlink-panels
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :shortcuts="shortcuts"
            :size="size"
          />
        </el-form-item>
        <el-form-item prop="searchDate" label="选择日期" v-if="roleId === 1">
          <el-date-picker v-model="formData.startWeekDate" type="week" format="YYYY年ww周" placeholder="选择开始周" />
          <p style="margin: 10px">至</p>
          <el-date-picker v-model="formData.endWeekDate" type="week" format="YYYY年ww周" placeholder="选择结束周" />
        </el-form-item>

        <el-form-item prop="dataState" label="订单状态">
          <el-select v-model="formData.orderState" clearable filterable placeholder="请选状态" style="width: 240px">
            <el-option v-for="item in codeList" :key="item.code" :label="item.state" :value="item.code" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="creatData">生成</el-button>
      </template>
    </el-dialog>

    <!-- 图表 -->
    <el-dialog v-model="dialogVisible" :title="'报表'" @close="resetForm" width="80%" v-if="seeState === 'dataShow'">
      <div
        @vnode-mounted="chartEvent.mounted"
        @vnode-unmounted="chartEvent.unmounted"
        class="eacharts1"
        ref="eacharts1"
        style="height: 500px"
        :style="{ width: chartOption.xAxis.data.length * 120 + 'px' }"
      />
    </el-dialog>

    <!-- 批量下载 -->
    <el-dialog v-model="dialogVisible3" title="下载密码" @close="resetForm1" width="50%" v-loading="loading">
      <el-form
        ref="formRef"
        :model="formData1"
        :rules="formRules1"
        label-width="100px"
        label-position="left"
        @keyup.enter="handleDownLoad"
      >
        <el-form-item prop="download" label="下载密码">
          <el-input v-model="formData1.download" placeholder="请输入下载密码" type="password" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible3 = false">取消</el-button>
        <el-button type="primary" @click="handleDownLoad">确认</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="dialogVisible1">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
:deep(.el-upload-list__item .el-icon--close-tip) {
  top: 20px;
  left: 10px;
  right: 0;
}
.doing {
  color: #b88230;
}
.error {
  color: red;
}
.success {
  color: #67c23a;
}
.again {
  color: #c45656;
}
:deep(.el-popper) {
  max-width: 50% !important;
}
.date-box {
  width: 340px !important;
}
.text-ellipsis {
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  -webkit-line-clamp: 3;
  display: -webkit-box;
  -webkit-box-orient: vertical;
}
:deep(.el-loading-parent--relative) {
  z-index: 199999 !important;
}
</style>
<style>
.el-popper.is-customized {
  /* Set padding to ensure the height is 32px */
  padding: 6px 12px;
  background: linear-gradient(90deg, rgb(159, 229, 151), rgb(204, 229, 129));
}

.el-popper.is-customized .el-popper__arrow::before {
  background: linear-gradient(45deg, #b2e68d, #bce689);
  right: 0;
}
</style>
